package util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JOptionPane;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class CargadorXML {

	private static CargadorXML instancia = null;
	
	private int error = 0;
	
	public static final int JDOMEXCEPTION = 1;
	public static final int NULLPOINTEREXCEPTION = 2;
	public static final int NOXMLFILE = 3;
	
	public static CargadorXML instancia() {
		if (instancia == null) {
			instancia = new CargadorXML();
		}
		return instancia;
	}
	
	public int getError(){
		return error;
	}
	
	public Element cargar(String filename) {
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new File(filename));
			return doc.getRootElement();

		} catch (JDOMException e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
			error = JDOMEXCEPTION;
		} catch (NullPointerException e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
			error = NULLPOINTEREXCEPTION;
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
			error = NOXMLFILE;
		}
		
		return null;
	}
	
	public void guardar(String filename, Element root) {
		Document doc = new Document(root);

		try {
			Format format = Format.getPrettyFormat();
			format.setEncoding("Cp1252");
			XMLOutputter outputter = new XMLOutputter(format);
			FileWriter writer = new FileWriter(filename);
			outputter.output(doc, writer);
			writer.close();
		} catch (java.io.IOException e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}

		return;
	}
	
	public String cargarString(Element e, String nombre) {
		String s = e.getChildText(nombre);
		return (s == null) ? "" : s;
	}

	public boolean cargarBoolean(Element e, String nombre) {
		return Boolean.valueOf(cargarString(e, nombre));
	}

	public Date cargarDate(Element e, String nombre, boolean defaultNull) {
		Date fecha = null;
		try {
			fecha = new SimpleDateFormat("ddMMyy").parse(cargarString(e, nombre));
		} catch (ParseException e1) {
			if (!defaultNull)
				fecha = new Date();
		}
		return fecha;
	}
}
